public class mergeSort {
    public static void mergeSort(int[] nums) {
        mergeFunc(nums,0,nums.length-1);
    }

    //递归版
    private static void mergeFunc(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = left + ((right - left) >> 1) ;
        //分解排序
        mergeFunc(nums,left,mid);
        mergeFunc(nums,mid+1,right);
        //合并
        merge(nums,left,mid,right);
    }
    //非递归版
    public static void mergeSortNor(int[] nums) {
        int gap = 1;
        //最外层循环 控制组数
        while(gap < nums.length) {
            //对每组进行排序
            for (int i = 0; i < nums.length; i = i + 2*gap) {
                int left = i;
                int mid = left + gap-1;
                if (mid >= nums.length) {
                    mid = nums.length - 1;
                }
                int right = mid + gap;
                if (right >= nums.length) {
                    right = nums.length - 1;
                }
                merge(nums,left,mid,right);
            }
            gap *= 2;
        }
    }

    private static void merge(int[] nums, int left, int mid, int right) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid + 1;
        int e2 = right;

        int[] tmp = new int[right-left+1];
        int k = 0;
        //保证两表都有数据
        while(s1 <= e1 && s2 <= e2) {
            if(nums[s1] <= nums[s2]) {
                tmp[k++] = nums[s1++];
            } else {
                tmp[k++] = nums[s2++];
            }
        }
        while(s1 <= e1) {
            tmp[k++] = nums[s1++];
        }
        while(s2 <= e2) {
            tmp[k++] = nums[s2++];
        }
        //拷贝到原数组
        for(int i=0;i<k;i++) {
            nums[i+left] = tmp[i];
        }
    }


}
